import 'package:flutter/material.dart';
import 'package:word_range_client/pojo/Result.dart';
import 'package:word_range_client/pojo/vo/WordBookVo.dart';

import '../../viewModels/WordBookViewModel.dart';
import '../../widgets/bookList/BookListItem.dart';

class BookListView extends StatelessWidget {
  const BookListView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("词书管理"),
      ),
      body: const _BookListBody(),
    );
  }
}

class _BookListBody extends StatefulWidget {
  const _BookListBody({super.key});

  @override
  State<_BookListBody> createState() => _BookListBodyState();
}

class _BookListBodyState extends State<_BookListBody> {

  List<Widget> _items = [];
  bool _isLoading = true;

  Future<List<WordBookVo>> getAllWordBookBaseInfo() async {
    WordBookViewModel wordBookViewModel = WordBookViewModel();
    Result result = await wordBookViewModel.getAllBookBaseInfo();
    if (result.code == 1) {
      return (result.data as List<dynamic>)
          .map((item) => WordBookVo.fromJson(item as Map<String, dynamic>))
          .toList();
    }
    return [];
  }

  void _initItems() async {
    final List<WordBookVo> allWordBookBaseInfo = await getAllWordBookBaseInfo();
    // 使用 setState 包裹数据更新
    setState(() {
      _items = [
        // const SelectedBookCardItem(), // 初始项
        ...allWordBookBaseInfo.map(
                (book) => BookListItem(wordBookVo: book)
        )
      ];
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    _initItems();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold( // 确保有完整的布局结构
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 转圈
              CircularProgressIndicator(),
              SizedBox(height: 10,),
              Text("Loading ...."),
            ],
          ),
        ),
      );
    }
    return GridView.extent(
      maxCrossAxisExtent: 600,
      childAspectRatio: 1/0.3,
      mainAxisSpacing: 10,
      crossAxisSpacing: 10,
      padding: const EdgeInsets.all(15),
      children: _items,
    );
  }
}

